package zuoye5;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class ServiceTest {
    public static void main(String[] args) {
        DatagramPacket dp=null;
        DatagramSocket ds=null;
        Scanner sc=new Scanner(System.in);
        try {
            ds=new DatagramSocket(8989);
            System.out.println("服务器 已开启，可以咨询了。");
            byte[]buf=new byte[1024];
            while (true) {
                dp=new DatagramPacket(buf,buf.length);
                System.out.println("receive1");

                ds.receive(dp);
                System.out.println("receive2");

                String mess=new String(dp.getData(),0,dp.getLength());
                InetAddress ia=dp.getAddress();
                System.out.println(ia.getHostAddress()+":"+dp.getPort()+"说："+mess);

                mess=sc.nextLine();
                byte[]data=mess.getBytes();

                dp=new DatagramPacket(data,data.length,dp.getSocketAddress());
                ds.send(dp);
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            ds.close();
        }
    }
}
